package com.example.administrator.basedemos.okhttp;

import android.net.Uri;

import com.example.administrator.basedemos.bean.ParamBean;
import com.example.administrator.basedemos.config.NetworkConfig;
import com.example.administrator.basedemos.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 创建者     ZCL
 * 创建时间   2018/3/14 17:42
 * 描述	      ${1.創建simple 創建builder
 * 2.從simple內創建newBUilder獲得builder對象
 * 3.builder內創建bulid得到simple對象
 * 4.builder內創建各種方法 如 get post method url addParams等等
 * 5.simple創建enqueue收尾
 * 6.創建關聯管理器 okhttpManger
 * }
 * <p>
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */

public class SimpleOkhttpClient {

    private static final String TAG = "SimpleOkhttpClient";
    private static Builder mBuilder;

    //设置成私有防止被外部创建
    private SimpleOkhttpClient() {
    }

    //因为我们自己封装不new对象所以用static不然和okhttp没区别
    public static Builder newBuilder() {
        mBuilder = new Builder();
        return mBuilder;
    }

    /**
     * client调用okhttpmanger完成衔接
     */
    public void enqueue(BaseCallBack callBack) {
        OkhttpManger.getInstance().reuqest(this, callBack);
    }

    /**
     * 获取request 对象 传递给manger   post或者get方式
     */
    protected Request builderRequest() throws JSONException {

        Request.Builder builder = new Request.Builder();
        if (mBuilder.method.equals("GET")) {
            /**
             因为是get方式后面可能有参数所以要进行拼接
             Process: com.example.administrator.basedemos, PID: 23992
             java.lang.IllegalStateException: url == null  -->mBuilder.url()造成的
             */
            builder.url(builderGetRequestParams());

            builder.get();

        } else if (mBuilder.method.equals("POST")) {

            builder.post(buliderRequestBody());
            builder.url(mBuilder.url);
        }
        return builder.build();
    }

    /**
     * 获取requestbody 表单或json
     *
     * @return
     * @throws JSONException
     */
    private RequestBody buliderRequestBody() throws JSONException {
        if (mBuilder.isJson) {
            //参数json格式创建json对象放入参数
            JSONObject jsonObject = new JSONObject();

            for (ParamBean p : mBuilder.mParams) {
                jsonObject.put(p.getKEY(), p.getValue());
            }

            String json = jsonObject.toString();
            LogUtil.util(TAG, "SimpleRequestJson--------------" + json);

            //通过requestbody.create 将数据以json格式发送
            return RequestBody.create(NetworkConfig.JSON, json);
        } else {
            //不是json则用fomr表单直接发送
            FormBody.Builder builder = new FormBody.Builder();
            //将builder表单进行拼接
            for (ParamBean p : mBuilder.mParams) {
                builder.add(p.getKEY(), p.getValue() == null ? "" : p.getValue().toString());
            }

            return builder.build();
        }
    }

    private String builderGetRequestParams() {
        if (mBuilder.mParams.size() <= 0)
            return this.mBuilder.url;
        /**
         * 这里的parse方法返回的是一个URI类型，通过这个URI可以访问一个网络上或者是本地的资源
         * 代码里需要构造一个uri的时候，建议的做法是通过Uri.Builder来做，而不是简单的字符串拼接，
         * 因为常常简单的case字符串拼接是可以的，一旦涉及到复杂的、特殊字符需要url encode的就不能很好的work。
         * 今天的是Uri.Builder的appendQueryParameter方法
         */
        Uri.Builder builder = Uri.parse(mBuilder.url).buildUpon();
        for (ParamBean p : mBuilder.mParams) {
            builder.appendQueryParameter(p.getKEY(), p.getValue() == null ? "" : p.getValue().toString());
        }

        String url = builder.build().toString();

        return url;
    }

    public static class Builder {
        String               url;
        String               method;
        ArrayList<ParamBean> mParams;
        ArrayList<ParamBean> mHeaders;
        boolean              isJson;

        public Builder() {
            method = "GET";
            mParams = new ArrayList<>();
        }


        public SimpleOkhttpClient build() {
            return new SimpleOkhttpClient();
        }

        public Builder get() {
            method = "GET";
            return this;
        }

        /**
         * form表單
         *
         * @return
         */
        public Builder postForm() {
            method = "POST";
            return this;
        }

        /**
         * JSON格式
         *
         * @return
         */
        public Builder postJson() {
            isJson = true;
            method = "POST";
            return postForm();
        }


        public Builder url(String urls) {
            this.url = urls;
            return this;
        }

        public Builder method(String meth) {
            method = meth;
            return this;
        }

        public Builder addParam(String key, String value) {
            if (mParams == null)
                mParams = new ArrayList<>();

            mParams.add(new ParamBean(key, value));
            return this;
        }

        public Builder addheader(String key, String value) {
            if (mHeaders == null)
                mHeaders = new ArrayList<>();

            mHeaders.add(new ParamBean(key, value));
            return this;
        }
    }
}
